package example

import (
	"gitee.com/windwolfs/battle"
	"gitee.com/windwolfs/battle/client"
	"gitee.com/windwolfs/battle/room"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Server struct {
	*battle.Server
	clientPool *client.SessionPool
	roomPool   *room.Pool
}

func New() *Server {
	return &Server{
		Server: battle.New("0.0.0.0", 8080),
		clientPool: &client.SessionPool{
			New: func(c *gin.Context, playerId string) client.Client {
				return &Player{
					Session:  client.NewSession(),
					Integral: 0,
				}
			},
		},
		roomPool: &room.Pool{
			New: func(roomId string) room.Room {
				return NewRoom(roomId)
			},
		},
	}
}

// Run
// 启动服务器
func (p *Server) Run() error {
	p.Engine.GET("/websocket/conn", p.Upgrade)
	return p.Server.Run()
}

// Upgrade
// 这个相当于TCP的 Accept 但是接收逻辑得自己写
func (p *Server) Upgrade(c *gin.Context) {
	var request Voucher

	if err := request.Bind(c); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": err.Error()})
		return
	}

	//	创建客户端
	cl := p.clientPool.Get(c, request.PlayerId)

	//	获取房间并加入房间
	r := p.roomPool.Get(request.RoomId)
	r.Join(cl)

	//	开启房间数据轮询
	r.Pull(cl)

	//	结束后销毁客户端
	p.clientPool.Destroy(request.PlayerId)
}
